<template>
  <div class="history-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>浏览历史管理</span>
          <el-button type="primary" @click="loadHistory">刷新</el-button>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="图片ID">
          <el-input
            v-model="searchForm.imageId"
            placeholder="请输入图片ID"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row" v-if="stats">
        <el-col :span="6">
          <el-statistic title="总浏览数" :value="stats.total" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日浏览" :value="stats.today" />
        </el-col>
      </el-row>

      <!-- 浏览历史列表 -->
      <el-table
        v-loading="loading"
        :data="historyList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="200" />
        <el-table-column prop="imageId" label="图片ID" width="100" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageThumbnail || row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 80px"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="imageTitle"
          label="图片标题"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="viewedAt" label="浏览时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";

const loading = ref(false);
const historyList = ref([]);
const stats = ref(null);

const searchForm = ref({
  userId: "",
  imageId: "",
});

const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
});

onMounted(() => {
  loadHistory();
  loadStats();
});

// 加载浏览历史列表
function loadHistory() {
  loading.value = true;

  const params = {
    page: pagination.value.page,
    pageSize: pagination.value.pageSize,
  };

  if (searchForm.value.userId) {
    params.userId = searchForm.value.userId;
  }

  if (searchForm.value.imageId) {
    params.imageId = searchForm.value.imageId;
  }

  request
    .get("/history", { params })
    .then((res) => {
      historyList.value = res.list || [];
      pagination.value.total = res.total || 0;
    })
    .catch((err) => {
      ElMessage.error(err.message || "加载失败");
    })
    .finally(() => {
      loading.value = false;
    });
}

// 加载统计信息
function loadStats() {
  request
    .get("/history/stats")
    .then((res) => {
      stats.value = res;
    })
    .catch((err) => {
      console.error("加载统计信息失败:", err);
    });
}

// 搜索
function handleSearch() {
  pagination.value.page = 1;
  loadHistory();
}

// 重置
function handleReset() {
  searchForm.value = {
    userId: "",
    imageId: "",
  };
  handleSearch();
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm(`确定要删除这条浏览历史吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      request
        .delete(`/history/${row.id}`)
        .then(() => {
          ElMessage.success("删除成功");
          loadHistory();
          loadStats();
        })
        .catch((err) => {
          ElMessage.error(err.message || "删除失败");
        });
    })
    .catch(() => {});
}

// 分页变化
function handleSizeChange(val) {
  pagination.value.pageSize = val;
  pagination.value.page = 1;
  loadHistory();
}

function handlePageChange(val) {
  pagination.value.page = val;
  loadHistory();
}
</script>

<style scoped>
.history-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}
</style>
